package order

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"goskeleton/app/model"
	"goskeleton/app/utils/response"
	"math/rand"
	"strconv"
	"time"
)

type Order struct {
	ProductId   int    `json:"product_id"`
	BuyerOpenId string `json:"buyer_open_id"`
}

// 修改 app/http/controller/order/order.go 中的 CreateOrder 方法
func (o *Order) CreateOrder(c *gin.Context) {
	var orderInfo Order
	if err := c.ShouldBindJSON(&orderInfo); err != nil {
		response.ErrorParam(c, err)
		return
	}

	order := model.CreateOrderFactory("mysql")
	orders, err := order.GetOrderByProductIdAndBuyerOpenId(orderInfo.ProductId, orderInfo.BuyerOpenId)
	if err != nil {
		response.ErrorParam(c, "数据库查询错误")
		return
	}
	if len(orders) > 0 {
		response.ErrorParam(c, "该订单已经创建，请勿重复创建")
		return
	}

	product := model.CreateProductFactory("mysql").GetProductById(strconv.Itoa(orderInfo.ProductId))

	timestamp := time.Now().UnixNano() / int64(time.Millisecond)
	randNum := rand.New(rand.NewSource(timestamp)).Intn(1000000)
	orderNo := fmt.Sprintf("%d%d%06d", orderInfo.ProductId, timestamp, randNum)

	createdOrder := order.CreateOrder(
		orderInfo.ProductId,
		orderInfo.BuyerOpenId,
		product.(map[string]interface{})["seller_open_id"].(string),
		product.(map[string]interface{})["address"].(string),
		product.(map[string]interface{})["price"].(string),
		orderNo,
	)

	// 返回订单详情
	response.Success(c, "订单创建成功", createdOrder)
}

// 更具TradeId获取商品信息
func (o *Order) GetProductInfo(context *gin.Context) {
	tradeId := context.Query("tradeId")
	product := model.CreateOrderFactory("mysql").GetProductInfo(tradeId)
	response.Success(context, "获取商品信息成功", product)

}

func (o *Order) QueryOrders(context *gin.Context) {
	openId := context.Query(`openId`)
	//根据openId去订单表查询购买者的订单
	orders, _ := model.CreateOrderFactory("mysql").QueryOrders(openId)

	response.Success(context, "获取订单成功", orders)

}

func (o *Order) CancelOrder(context *gin.Context) {
	//根据trade_id去删除相关的订单
	model.CreateOrderFactory("mysql").CancelOrder(context.Query(`trade_id`))
	response.Success(context, "取消订单成功", nil)

}
